package com.cj.mobile.iabp.mvp.ui.activity;

import static com.jess.arms.utils.Preconditions.checkNotNull;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.pickerview.TimePickerView;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.cj.mobile.iabp.R;
import com.cj.mobile.iabp.app.global.Constant;
import com.cj.mobile.iabp.app.utils.CommonUtils;
import com.cj.mobile.iabp.app.utils.EventBusTags;
import com.cj.mobile.iabp.app.utils.GlideLoader;
import com.cj.mobile.iabp.di.component.DaggerAddRemoveInfoComponent;
import com.cj.mobile.iabp.mvp.contract.AddRemoveInfoContract;
import com.cj.mobile.iabp.mvp.model.entity.MainEvent;
import com.cj.mobile.iabp.mvp.model.entity.RemoveInfo;
import com.cj.mobile.iabp.mvp.presenter.AddRemoveInfoPresenter;
import com.cj.mobile.iabp.mvp.ui.adapter.UploadCertificateAdapter;
import com.cj.mobile.iabp.mvp.ui.widget.FlexboxRadioGroup;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.lcw.library.imagepicker.ImagePicker;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created on 2025/09/29 22:22
 * 新增撤机信息
 *
 * @author Love_xie
 * module name is AddRemoveInfoActivity
 */
@RuntimePermissions
public class AddRemoveInfoActivity extends BaseActivity<AddRemoveInfoPresenter> implements AddRemoveInfoContract.View {
    /*----------------------------------------------------------------控件信息----------------------------------------------------------------*/
    @BindView(R.id.txvi_addremoveinfo_code)
    TextView txviCode;                                                                              // 登记号
    @BindView(R.id.txvi_addremoveinfo_name)
    TextView txviName;                                                                              // 患者姓名
    @BindView(R.id.group_addremoveinfo_concern)
    RadioGroup rgConcern;                                                                           // 关注
    @BindView(R.id.txvi_addremoveinfo_removetime)
    TextView txviRemoveTime;                                                                        // 撤机时间
    @BindView(R.id.imvi_addremoveinfo_removetime)
    ImageView imviRemoveTime;
    @BindView(R.id.edit_addremoveinfo_runtime)
    TextView editRunTime;                                                                           // 运行时间
    @BindView(R.id.group_addremoveinfo_state)
    RadioGroup rgState;                                                                             // 患者状态
    @BindView(R.id.group_addremoveinfo_complication)
    FlexboxRadioGroup rgComplication;                                                                      // 并发症
    @BindView(R.id.edit_addremoveinfo_othertext)
    EditText editOtherText;                                                                         // 其他情况填写
    @BindView(R.id.revi_addremoveinfo_img)
    RecyclerView reviImgList;                                                                       // 特殊或异常情况拍照
    /*----------------------------------------------------------------业务信息----------------------------------------------------------------*/
    // 对话框
    private MaterialDialog mDialog;
    // 撤机时间
    private Date removeData;
    // 图片适配器
    @Inject
    UploadCertificateAdapter mImgAdapter;
    @Inject
    GridLayoutManager mGridLayoutManager;

    @Override
    protected void onDestroy() {
        KeyboardUtils.unregisterSoftInputChangedListener(getWindow());
        DefaultAdapter.releaseAllHolder(reviImgList);
        if (mDialog != null) {
            this.mDialog.dismiss();
        }
        super.onDestroy();

        this.mDialog = null;
        this.mImgAdapter = null;
        this.mGridLayoutManager = null;
        this.removeData = null;
    }

    /**
     * 根据主题使用不同的颜色。
     * 如果想要纯透明，则需要重写此方法，返回值为 -1 即可。
     */
    public int useStatusBarColor() {
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(android.R.color.white, typedValue, true);
        return typedValue.data;
    }

    /**
     * 将状态栏改为浅色模式(状态栏 icon 和字体会变成深色)
     */
    public boolean useLightStatusBar() {
        return true;
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerAddRemoveInfoComponent
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_add_remove_info;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        setTitle("撤机信息");

        removeData = new Date();

        // 初始化Loading对话框
        mDialog = new MaterialDialog.Builder(this).content(R.string.common_execute).progress(true, 0).build();

        initRecyclerView();

        rgComplication.setOnCheckedChangeListener((group, checkedId) -> {
            editOtherText.setVisibility(group.getCheckedRadioButtonId() == R.id.radio_addremoveinfo_complication_other ? View.VISIBLE : View.GONE);
            editOtherText.setText("");
        });

        if (mPresenter != null) {
            mPresenter.initData(getIntent().getExtras());
        }
    }

    private void initRecyclerView() {
        ArmsUtils.configRecyclerView(reviImgList, mGridLayoutManager);
        reviImgList.setAdapter(mImgAdapter);
        mImgAdapter.setDefaultBg(false);
    }

    @Subscriber(tag = EventBusTags.HOME_TAG, mode = ThreadMode.POST)
    private void eventBusEvent(MainEvent mainEvent) {
        if (mainEvent.getCode() == EventBusTags.UPLOAD_IMAGE_TAG) {
            // 上传图片
            AddRemoveInfoActivityPermissionsDispatcher.getCameraWithPermissionCheck(this);
        } else if (mainEvent.getCode() == EventBusTags.DELETE_IMAGE_TAG) {
            // 删除照片
            if (mImgAdapter != null) {
                mImgAdapter.getInfos().remove(mainEvent.getPosition());
                mImgAdapter.notifyDataSetChanged();
            }
        }
    }

    @OnClick({
            R.id.lila_addremoveinfo_removetime,                                                     // 撤机时间
            R.id.imvi_addremoveinfo_removetime,
            R.id.btn_addremoveinfo_compute,                                                         // 计算 运行时间
            R.id.btn_addremoveinfo_save,                                                            // 暂存
            R.id.btn_addremoveinfo_submit,                                                          // 提交
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lila_addremoveinfo_removetime:                                                // 撤机时间
                onRemoveDate();
                break;
            case R.id.imvi_addremoveinfo_removetime:
                txviRemoveTime.setText("");
                imviRemoveTime.setVisibility(View.GONE);
                break;
            case R.id.btn_addremoveinfo_compute:                                                    // 计算 运行时间
                if (TextUtils.isEmpty(txviRemoveTime.getText().toString())) {
                    showMessage("请选择撤机时间！");
                    return;
                }
                // 计算运行时间
                if (mPresenter != null) {
                    mPresenter.computeRunTime(txviRemoveTime.getText().toString());
                }
                break;
            case R.id.btn_addremoveinfo_save:                                                       // 暂存
                if (!CommonUtils.isDoubleClick()) {
                    onSubmit("0");
                }
                break;
            case R.id.btn_addremoveinfo_submit:                                                     // 提交
                if (!CommonUtils.isDoubleClick()) {
                    onSubmit("1");
                }
                break;
        }
    }

    /**
     * 提交
     */
    private void onSubmit(String pre) {
        if (mPresenter != null) {
            mPresenter.btnSubmit(pre,
                    "", "是",
                    txviRemoveTime.getText().toString(),
                    editRunTime.getText().toString(),
                    isConcern(),
                    isAlive(),
                    moreDiag(),
                    editOtherText.getText().toString(), mImgAdapter.getInfos());
        }
    }

    /**
     * 并发症
     */
    private String moreDiag() {
        if (rgComplication.getCheckedRadioButtonId() != -1) {
            if (rgComplication.getCheckedRadioButtonId() == R.id.radio_addremoveinfo_complication_not) {
                return "无";
            } else if (rgComplication.getCheckedRadioButtonId() == R.id.radio_addremoveinfo_complication_qnlq) {
                return "球囊漏气";
            } else if (rgComplication.getCheckedRadioButtonId() == R.id.radio_addremoveinfo_complication_ncz) {
                return "脑卒中";
            } else if (rgComplication.getCheckedRadioButtonId() == R.id.radio_addremoveinfo_complication_fmhcx) {
                return "腹膜后出血";
            } else if (rgComplication.getCheckedRadioButtonId() == R.id.radio_addremoveinfo_complication_ccbwc) {
                return "穿刺部位出";
            } else if (rgComplication.getCheckedRadioButtonId() == R.id.radio_addremoveinfo_complication_jz) {
                return "截肢";
            } else if (rgComplication.getCheckedRadioButtonId() == R.id.radio_addremoveinfo_complication_xzqxwkcl) {
                return "下肢缺血外科处理";
            } else {
                return "其他(详述)";
            }
        }
        return "";
    }

    private String isAlive() {
        if (rgState.getCheckedRadioButtonId() != -1) {
            if (rgState.getCheckedRadioButtonId() == R.id.radio_addremoveinfo_state_yes) {
                return "存活";
            } else {
                return "死亡";
            }
        }
        return "";
    }

    /**
     * 是否关注
     */
    private String isConcern() {
        if (rgConcern.getCheckedRadioButtonId() != -1) {
            if (rgConcern.getCheckedRadioButtonId() == R.id.radio_addremoveinfo_concern_yes) {
                return "是";
            } else {
                return "否";
            }
        }

        return "";
    }

    /**
     * 撤机时间
     */
    private void onRemoveDate() {
        // 起始日期
        Calendar startDate = Calendar.getInstance();
        // 设置年份
        startDate.set(Calendar.YEAR, 1900);

        // 终止日期(今天+100年)
        Calendar endDate = Calendar.getInstance();
        endDate.add(Calendar.YEAR, 100);

        TimePickerView pvOptions = new TimePickerView.Builder(this, (date, v) -> {
            this.removeData = date;
            // yyyy-MM-dd HH:mm:ss
            txviRemoveTime.setText(TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd HH:mm")));
            imviRemoveTime.setVisibility(View.VISIBLE);
        })
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(20)//确定和取消文字大小
                .setSubmitColor(ContextCompat.getColor(this, R.color.colorPrimary))//确定按钮文字颜色
                .setCancelColor(ContextCompat.getColor(this, R.color.colorPrimary))//取消按钮文字颜色
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
//                .setCyclic(true, true, true)//循环与否
                .setType(new boolean[]{true, true, true, true, true, false}) //年月日时分秒 的显示与否，不设置则默认全部显示
                .setRangDate(startDate, endDate)
                .setContentSize(16)
                .build();

        // 设置数据
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(removeData);
        pvOptions.setDate(calendar);
        pvOptions.show();
    }

    /**
     * 选择图片
     */
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    public void getCamera() {
        FileUtils.createOrExistsDir(Constant.IMAGE_PATH);

        ImagePicker.getInstance()
                .setTitle("图片")//设置标题
                .showCamera(true)//设置是否显示拍照按钮
                .showImage(true)//设置是否展示图片
                .showVideo(false)//设置是否展示视频
                .filterGif(true)//设置是否过滤gif图片
                .setMaxCount(getImageNum())//设置最大选择图片数目(默认为1，单选)
                .setSingleType(true)//设置图片视频不能同时选择
                .setImagePaths(galleryImages)
                .setImageLoader(new GlideLoader(getApplicationContext()))//设置自定义图片加载器
                .start(this, Constant.SELECT_IMG_GSMT_REQUESTCODE);
    }

    // 图库图片
    private ArrayList<String> galleryImages = new ArrayList<>();
    // 网络图片
    private ArrayList<String> networkImages = new ArrayList<>();

    /**
     * 图片可选数量
     * 逻辑：共可以选3张，假设列表中存在网络图片，则需要减去已存在的图片数量
     */
    private int getImageNum() {
        galleryImages.clear();
        networkImages.clear();
        // 一共可选图片数量
        int total = 3;
        // 网络图片数量
        int networkNum = 0;

        for (String str : mImgAdapter.getInfos()) {
            if (str.contains("http")) {
                networkNum++;
                networkImages.add(str);
            } else {
                galleryImages.add(str);
            }
        }

        return total - networkNum;
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onCameraDenied() {
        // 用户拒绝权限时的处理
        showMessage("需要相机和存储权限才能选择图片");
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onCameraNeverAskAgain() {
        // 用户选择"不再询问"时的处理
        new MaterialDialog.Builder(this)
                .content("需要相机和存储权限才能选择图片，请在设置中手动开启权限")
                .positiveText("去设置")
                .negativeText("取消")
                .onPositive((dialog, which) -> {
                    // 引导用户到应用设置页面开启权限
                    CommonUtils.goToAppSettings(this);
                })
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            // 照片
            if (requestCode == Constant.SELECT_IMG_GSMT_REQUESTCODE) {
                // 清空以前图片
                mImgAdapter.getInfos().clear();
                // 展示图片
                uploadData(data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES), requestCode);
            }
        }
    }

    /**
     * 压缩失败 》 加载图片 》 添加默认选择的图片
     */
    private void uploadData(ArrayList<String> path, int requestCode) {
        // 照片
        if (requestCode == Constant.SELECT_IMG_GSMT_REQUESTCODE) {
            // 接收当前选中的图
            mImgAdapter.setData(networkImages);
            mImgAdapter.setData(path);
            // 接下来展示图片
            mImgAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AddRemoveInfoActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void showRemoveInfo(String code, String name, RemoveInfo info) {
        txviCode.setText(CommonUtils.isEmptyReturnStr(code, "暂无"));
        txviName.setText(CommonUtils.isEmptyReturnStr(name));

        if (info != null) {
            // 关注
            if (!TextUtils.isEmpty(info.getFocuse())) {
                if (info.getFocuse().equals("是")) {
                    ((RadioButton) findViewById(R.id.radio_addremoveinfo_concern_yes)).setChecked(true);
                } else {
                    ((RadioButton) findViewById(R.id.radio_addremoveinfo_concern_not)).setChecked(true);
                }
            }

            // 撤机时间
            if (!TextUtils.isEmpty(info.getRemoveTime())) {
                txviRemoveTime.setText(info.getRemoveTime());
                imviRemoveTime.setVisibility(View.VISIBLE);
            }
            // 运行时间
            editRunTime.setText(CommonUtils.isEmptyReturnStr(info.getRunTimeStr()));

            // 撤机状态
            if (!TextUtils.isEmpty(info.getIsAlive())) {
                if (info.getIsAlive().equals("存活")) {
                    ((RadioButton) findViewById(R.id.radio_addremoveinfo_state_yes)).setChecked(true);
                } else {
                    ((RadioButton) findViewById(R.id.radio_addremoveinfo_state_not)).setChecked(true);
                }
            }

            // 并发症
            if (!TextUtils.isEmpty(info.getMoreDiag())) {
                if (info.getMoreDiag().equals("无")) {
                    ((RadioButton) findViewById(R.id.radio_addremoveinfo_complication_not)).setChecked(true);
                } else if (info.getMoreDiag().equals("球囊漏气")) {
                    ((RadioButton) findViewById(R.id.radio_addremoveinfo_complication_qnlq)).setChecked(true);
                } else if (info.getMoreDiag().equals("脑卒中")) {
                    ((RadioButton) findViewById(R.id.radio_addremoveinfo_complication_ncz)).setChecked(true);
                } else if (info.getMoreDiag().equals("腹膜后出血")) {
                    ((RadioButton) findViewById(R.id.radio_addremoveinfo_complication_fmhcx)).setChecked(true);
                } else if (info.getMoreDiag().equals("穿刺部位出")) {
                    ((RadioButton) findViewById(R.id.radio_addremoveinfo_complication_ccbwc)).setChecked(true);
                } else if (info.getMoreDiag().equals("截肢")) {
                    ((RadioButton) findViewById(R.id.radio_addremoveinfo_complication_jz)).setChecked(true);
                } else if (info.getMoreDiag().equals("下肢缺血外科处理")) {
                    ((RadioButton) findViewById(R.id.radio_addremoveinfo_complication_xzqxwkcl)).setChecked(true);
                } else if (info.getMoreDiag().equals("其他(详述)")) {
                    ((RadioButton) findViewById(R.id.radio_addremoveinfo_complication_other)).setChecked(true);
                    editOtherText.setVisibility(View.VISIBLE);
                    editOtherText.setText(info.getMoreDiagTxt());
                }

            }

            if (!TextUtils.isEmpty(info.getImages())) {
                String[] path = info.getImages().split(",");

                // 接收当前选中的图
                mImgAdapter.setData(path);
                // 接下来展示图片
                mImgAdapter.notifyDataSetChanged();
            }

        }
    }

    @Override
    public void loadRunTime(String runTime) {
        editRunTime.setText(CommonUtils.isEmptyReturnStr(runTime));
    }


    @Override
    public void showLoadingSubmit() {
        if (mDialog != null)
            mDialog.show();
    }

    @Override
    public void hideLoadingSubmit() {
        if (mDialog != null)
            mDialog.hide();
    }
}